articles

Home / DeveloperSection / Articles / Implementing Country List in TableView

Implementing Country List in TableView

Tarun Kumar3472 19-Nov-2015

Previous article: Implementing UISearchBar in Table View 

 

We will continue where we finish our previous project, here we will implement code in CountryListViewController class to display country list. For the country list we are using sqlite database. We have a COUNTRY table in sqlite database, that we use to display country name with its country Code.

In CountryListViewController.h file we will import 'sqlite3.h' file. this file is responsible for creating SQLite database instance that we use in our application. 


Follow the steps:


1.    Select 'CountryListViewController' and implement following code into 'viewDidLoad' method(will will focus on important codes that we will use in our code):


// using this code we are checking, if the file is available on the selected databasePath then the condition will be true.


if([filemgr fileExistsAtPath: databasePath ] == YES)

// in this code countryDB is the reference of sqlite database. 'sqlite3_open' will open the database connection


if (sqlite3_open([databasePath UTF8String], & countryDB) == SQLITE_OK)

   

 // 'sqlite3_prepare_v2' is responsible for executing query in the sqlite database.   

if(sqlite3_prepare_v2(countryDB, select_stmt, -1,& stmt, NULL)==SQLITE_OK)

 

  // this while loop executes according to the no of rows in the selected table.

while(sqlite3_step(stmt) == SQLITE_ROW)

// this code is used to build the path to the database file         

databasePath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent: @"country.db"]

 

  // this code will fetch the second column value form the database table.

NSString *Name = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(stmt,1)];


 // this will close the connection of sqlite database.

sqlite3_close(countryDB);


 2.    now, implement the 'numberOfSectionsInTableView:' delegate method of table view return value 1. because at this time we need only one section in our table view.

3.    now, implement the 'numberOfRowsInSection:' delegate method of table view, return the total rows needed in the table view, return like this:


return [countryRecords count];


4. now, implement the 'cellForRowAtIndexPath:' delegate method of table view, is responsible for creating cell and displaying data in each cell. In this method we will define a static identifier for each cell that is used to differentiate each cell from other section's cell. 

 

That's it,

our code implementation for displaying countries name is completed.

Now, click the 'Run' button of Xcode to run the application, after that click on 'Continue' button, next click on 'Search Country' button, now our 'CountryListViewController' will be open with the country list data that we are currently modified.(it will look like this):

Implementing Country List in TableView

 

Here is the source code:

CountryListViewController.h file

#import <UIKit/UIKit.h>

#import "sqlite3.h"

 

@interface CountryListViewController : UIViewController<UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate, UISearchBarDelegate>

{

sqlite3 *countryDB;

sqlite3_stmt *stmt;

NSString *databasePath;

NSString *docsDir;

NSArray *dirPaths;

NSMutableArray *countryRecords;

}

@property (nonatomic,strong) NSArray *sectionTitles;

@property(nonatomic,strong) NSString *databasePath;

@property(nonatomic,strong) NSString *docsDir;

@property(nonatomic,strong) NSArray *dirPaths;

@property(nonatomic, retain) IBOutlet UITableView *tableView;

@property (nonatomic, retain) NSMutableArray *searchResults;

 

@end

CountryListViewController.m file


#import "CountryListViewController.h"

#import "CountryListController.h"

 

@interface CountryListViewController ()<UISearchBarDelegate>

@end

 

@implementation CountryListViewController

@synthesize databasePath,docsDir,dirPaths,sectionTitles;

@synthesize searchResults;

 

static NSString * const reuseIdentifier = @"Cell";

 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

if (self) {

// Custom initialization

}

return self;

}

 

- (void)viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view.

_tableView.delegate=self;

_tableView.dataSource=self;

countryRecords = [[NSMutableArray alloc]init];

dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,

NSUserDomainMask, YES);

docsDir = [dirPaths objectAtIndex:0];

 

// Build the path to the database file

databasePath = [[NSString alloc]initWithString:

[docsDir stringByAppendingPathComponent: @"country.db"]];

NSFileManager *filemgr = [NSFileManager defaultManager];

if([filemgr fileExistsAtPath: databasePath ] == YES)

{

if (sqlite3_open([databasePath UTF8String],& countryDB) == SQLITE_OK)

{

NSString *selectSQL = [NSString stringWithFormat:

@"SELECT ID,NAME,PHONECODE FROM COUNTRY;"];

const char *select_stmt = [selectSQL UTF8String];

if(sqlite3_prepare_v2(countryDB, select_stmt, -1,& stmt, NULL)==SQLITE_OK)

{

while(sqlite3_step(stmt) == SQLITE_ROW)

{

long Id = sqlite3_column_int64(stmt, 0);

NSString *Name = [[NSString alloc] initWithUTF8String: (const char *)

sqlite3_column_text(stmt,1)];

NSString *Code = [[NSString alloc] initWithUTF8String: (const char *)

sqlite3_column_text(stmt,2)];

CountryListController *countryObj = [[CountryListController alloc] init];

[countryObj setCountryNameAndCode:Id andName:Name andCode:Code];

[countryRecords addObject:countryObj];

}

}

}

sqlite3_finalize(stmt);

sqlite3_close(countryDB);

} else {

NSLog(@"File not Exist");

}

[self fetchSectionTitle];

}

 

- (void)fetchSectionTitle{

NSMutableSet *set = [[NSMutableSet alloc]init];

for(CountryListController *obj in countryRecords)

{

 [set addObject:[[obj CountryName] substringToIndex:1]];

NSLog(@"%@",set);

}

sectionTitles = [[set allObjects] sortedArrayUsingSelector:

@selector(caseInsensitiveCompare:)]; 

}

 

// table delegate method used to count not of rows for each section

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

return [countryRecords count];

}

 

// table delegate method used to set cell in each row with its values

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

static NSString *simpleTableIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

CountryListController *countryObj = [countryRecords objectAtIndex:indexPath.row];

cell.textLabel.text = countryObj.CountryName;

cell.detailTextLabel.text = countryObj.Code;

return cell;

}

 

-(void)viewWillAppear:(BOOL)animated

{

[super viewWillAppear:animated];

}

 

- (void)didReceiveMemoryWarning

{

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

 

@end

 

Next we will learn how to create sections for displaying country name in ascending order in the table view: Implementing Sections in Country List in TableView


Updated 07-Sep-2019

Leave Comment

Comments

Liked By